import { baseUrl } from "../env.js";

function objectToQueryString(formData) {
    const params = new URLSearchParams();

    formData.forEach((value, key) => {
        params.append(key, value);
    });

    return params.toString();
}

document
    .querySelector("#loginForm")
    .addEventListener("submit", function (event) {
        event.preventDefault();
        event.submitter.disabled = true;

        const formData = new FormData(this);

        fetch(`${baseUrl}/login?${objectToQueryString(formData)}`, {
            method: "GET",
        })
            .then((res) => res.json())
            .then((data) => {
                console.log();
                alert(data.msg);
                if (data.code == 200) {
                    event.target.reset();
                }
            })
            .catch((err) => {
                alert("登陆失败");
                console.log(err);
            })
            .finally(() => {
                event.submitter.disabled = false;
            });
    });

document
    .querySelector("#registerForm")
    .addEventListener("submit", function (event) {
        event.preventDefault();
        event.submitter.disabled = true;

        const formData = new FormData(this);

        fetch(`${baseUrl}/register?${objectToQueryString(formData)}`, {
            method: "GET",
        })
            .then((res) => res.json())
            .then((data) => {
                alert(data.msg);
                if (data.code == 200) {
                    event.target.reset();
                }
            })
            .catch((err) => {
                console.log(err);
                alert("注册失败");
            })
            .finally(() => {
                event.submitter.disabled = false;
            });
    });
